package site.assad.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import site.assad.dao.UserDao;
import site.assad.domain.User;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/15 11:37
 * Description: 
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private final static Logger log = LogManager.getLogger();

    //获取 user
    public User getUser(int userId) {
        //当 redis 缓存中存在 user，返回该 user
        User userCache = (User) redisTemplate.opsForValue().get(userId+"");
        if (userCache != null)
            return userCache;
        //当 redis 缓存中不存在 user，从数据库中获取 redis ，同时将 user 写入缓存
        log.info("real query user from DB");
        User user = userDao.getUserById(userId);
        if(user != null )
            redisTemplate.opsForValue().set(user.getId()+"",user);
        return user;
    }

    //将 userId 对应的 User 从缓存中删除
    public void removeUserFromCache(int userId){
        //缓存中删除 user
        redisTemplate.delete(userId+"");
        log.info("remove user "+ userId + " from cache");
    }

    //删除 user
    public void removeUser(int userId){
        removeUserFromCache(userId);
        userDao.deleteUserById(userId);
        log.info("remove user "+ userId + " from database");
    }

    //添加 user
    public void addUser(User user){
        if(userDao.addUser(user))
            redisTemplate.opsForValue().set(user.getId()+"",user);
    }

    //更新 user
    public void updateUser(User user){
        if(userDao.update(user))
            redisTemplate.opsForValue().set(user.getId()+"",user);
    }

}
